// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.data.sources

import android.content.Context
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.location.Location
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import xyz.apiote.bimba.czwek.data.ResultFlowItem
import xyz.apiote.bimba.czwek.data.exceptions.DataSourceMissingException
import xyz.apiote.bimba.czwek.data.exceptions.GeocodingFailedException
import xyz.apiote.bimba.czwek.data.traffic.PointOfInterest
import xyz.apiote.bimba.czwek.repo.Position

class GeocodingOfflineDataSource {
	fun queryPlaces(query: String, context: Context): Flow<ResultFlowItem> = flow {
		val db =
			try {
				SQLiteDatabase.openDatabase(
					context.getDatabasePath("geocoding").path,
					null,
					SQLiteDatabase.OPEN_READONLY
				)
			} catch (e: SQLException) {
				emit(DataSourceMissingException("could not open database: $e"))
				return@flow
			}

		val cursor = db.rawQuery(
			"select lat, lon from place_names join places using(id) where name = ?",
			arrayOf(query)
		)

		if (!cursor.moveToNext()) {
			cursor.close()
			db.close()
			emit(GeocodingFailedException())
			return@flow
		}

		val location = Location(null).apply {
			latitude = cursor.getDouble(0)
			longitude = cursor.getDouble(1)
		}
		cursor.close()
		db.close()

		emit(PointOfInterest(query, "", Position(location)))
	}
}